package com.siqi.hr.system.common.chan;

import com.siqi.hr.system.common.sql.SField;
import com.siqi.hr.system.common.sql.STable;
import com.siqi.hr.system.common.utils.Common;
import org.apache.commons.lang.StringUtils;

public class TSQLCountSelectStat extends TSQLSelectStat{
  public StringBuilder toSqlString(){
    if ((this.fieldChan == null) || (this.fieldChan.size() == 0)) throw new IllegalArgumentException("字段为空");

    StringBuilder sb = new StringBuilder();
    sb.append(" select distinct count(DISTINCT t_" + this.tableCode + ".id) from ").append(this.tableChan.toSqlString());

    getJoinTableByName(this.tableChan);

    authCondAppend(sb);

    sb.append(" where 1=1 ");

    if (this.conditionChan.size() > 0) {
      sb.append(" and ").append(this.conditionChan.toSqlString());
    }

    if (!this.authorityCond.equals("")) {
      sb.append(" and ").append(this.authorityCond);
    }

    //如果是使用bootstrap自带模糊查询功能
    if(this.isBootstrapQuery){
        appendBootstrapFilterSql(sb);
    }

    return sb;
  }

  public void init() {
      super.init();
      for (SField field : this.fieldChan) {
          if (field.isQuote()) {//如果是引用字段
              if (field.getQuoteTable() != null && StringUtils.equals(field.getQuoteTable().getName(),"sys_custom_entity")) {
                  STable table = new STable("sys_custom_entity",field.getName(), field.getTable().getByName());
                  this.tableChan.add(table);
              } else if (field.getName().indexOf("sys_custom_entity_type") != -1) {
                  STable table = new STable("sys_custom_entity_type",field.getName(), field.getTable().getByName());
                  this.tableChan.add(table);
              }else if (field.getName().contains("sys_custom_selectbox")) {
                  STable st = new STable("sys_custom_selectbox",field.getName(), field.getTable().getByName());
                  this.tableChan.add(st);
              } else if (field.isQuoteCustomTable()) {//如果是引用字段
                  STable table = new STable(Common.getFkTableNameByField(field.getName()),field.getName(), field.getTable().getByName());
                  this.tableChan.add(table);
              }
          } else if ((!field.getName().endsWith("_mutibox"))&& (SField.isSelectBox(field.getName()))) {//如果是下拉框字段
              STable st = new STable("sys_custom_selectbox", field.getName(),field.getTable().getByName());
              this.tableChan.add(st);
          }
      }
  }

  public TSQLCountSelectStat(){
  }

  public TSQLCountSelectStat(TSQLSelectStat tSelectStat) {
    setConditionChan(tSelectStat.getConditionChan());
    setFieldChan(tSelectStat.fieldChan);
    setTableChan(tSelectStat.getTableChan());
    setScope(tSelectStat.getScope());
    setTablecode(tSelectStat.getTablecode());
    setEmployee(tSelectStat.getEmployee());
    setDept(tSelectStat.getDept());
    setBootstrapQuery(tSelectStat.isBootstrapQuery());
    setSearchVal(tSelectStat.getSearchVal());
  }

}
